package org.blade.personal.controller.sys;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.blade.personal.component.Const;
import org.blade.personal.manager.sys.RoleManager;
import org.blade.personal.mode.sys.SystemRole;
import org.blade.personal.utils.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("role")
public class RoleController {

	@Autowired
	private RoleManager roleManager;

	/**
	 * 添加角色
	 * @return
	 */
	@RequestMapping("add")
	public ModelAndView addRoles(){
		ModelAndView to = new ModelAndView("role/role-mgr");
		to.addObject("title", "添加");
		return to;
	}

	@RequestMapping("toEdit")
	public ModelAndView toEdit(){
		
		ModelAndView to = new ModelAndView("role/role-edit");
		to.addObject("title", "编辑");
		return to;
	}
	
	@ResponseBody
	@RequestMapping("save")
	public int saveRoles(@RequestParam Map data){
		SystemRole role = new SystemRole();
		try {
			Long id = MapUtils.getLong(data, "id");
			String name = MapUtils.getString(data, "name");
			Integer type = MapUtils.getInteger(data, "type");
			role.setId(id);	
			role.setName(name);
			role.setType(type);	
			 roleManager.save(role);
			 return Const.Status.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Const.Status.FAIL;
	}
	
	/**
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("fetch")
	public Map fetchRoles(@RequestParam Map data){
		
		Pager<SystemRole> page = new Pager<SystemRole>();
		page.setCurrentPage(MapUtils.getLong(data, "page"));
		page.setPageSize(MapUtils.getLong(data, "pagesize"));
		String paramStr = MapUtils.getString(data, "param");
		Map temp = JSON.parseObject(paramStr, Map.class);
		Map param = temp == null ? new HashMap(): temp;
		
		//TODO roleManager.pagingQuery(page,param);
		//roleManager.pagingQuery(page,param);
		data.put("datas", page.getEntities());
		data.put("Total", page.getTotalCount());
		return data;
	}
	
	@ResponseBody
	@RequestMapping("delete")
	public int deleteRole(@RequestParam Map reqParam){
		String ids = MapUtils.getString(reqParam, "ids", "-1");
		return roleManager.removeByIds(ids);
	}
	
	@ResponseBody
	@RequestMapping("load")
	public SystemRole getRole(@RequestParam Map param){
		
		Long id = MapUtils.getLong(param, Const.System.ID);
		return roleManager.getById(id);
	}
}
